#!/usr/bin/env python

import os
import time

TEMPLATE_FILE       = 'template.html'
DATA_DIR            = os.path.join(os.path.dirname(__file__), '../../../data/log/delicious/')

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app


def bbody(req, user):
    control     = { 'bheader' : True, 'bbody' : True, 'bfooter' : True }
    hheader     = { }
    bbody       = None
    return_url  = None
    void        = { }

    params = { }

    params['y'] = req.get('y', time.strftime('%Y'))
    filename = '%s.txt' % params['y']
    if not os.path.exists(os.path.join(DATA_DIR, filename)):
        filename = sorted(os.listdir(DATA_DIR), reverse = True)[0]
        params['y'] = filename.split('.')[0]
    filenames = os.listdir(DATA_DIR)
    params['messages'] = [ ]
    if filename in filenames:
        for line in open(os.path.join(DATA_DIR, filename), 'r'):
            if not line.strip() or line[0] == '#':
                continue
            t = line[:-1].split('\t')
            td = t[0].split('-')
            d = { 
                'date'   : t[0],
                'date_f' : time.strftime('%B %d, %Y', (int(td[0]), int(td[1]), int(td[2]), 0, 0, 0, 0, 0, 0)),
                'title'  : t[1], 
                'url'    : t[2] 
            }
            params['messages'].append(d)
        params['messages'] = sorted(params['messages'], key = lambda x : '%s\t%s' % (x['date'], x['title']), reverse = True)

    if not params['messages']:
        del params['y']

    path = os.path.join(os.path.dirname(__file__), TEMPLATE_FILE)
    bbody = template.render(path, params)      

    return (control, hheader, bbody, return_url, void)

